﻿namespace EyeOpen.BomberMan
{
	using System;
	using System.Drawing;
	using System.IO;
	using System.Reflection;

	public static class AssemblyExtensions
	{
		public static string GetText(this Assembly assembly, string resourceName)
		{
			using (var stream = CreateStream(assembly, resourceName))
			{
				using (var reader = new StreamReader(stream))
				{
					return reader.ReadToEnd();
				}
			}
		}

		public static Bitmap GetBitmap(this Assembly assembly, string resourceName, bool makeTransparent = false)
		{
			using (var stream = CreateStream(assembly, resourceName))
			{
				var bitmap = new Bitmap(stream);

				if (makeTransparent)
				{
					bitmap.MakeTransparent(bitmap.GetPixel(0, 0));
				}

				return bitmap;
			}
		}

		/// <exception cref="ArgumentException"><c>ArgumentException</c>.</exception>
		public static Bitmap GetBitmap(this Assembly assembly, string resourceName, Size size, bool makeTransparent = false)
		{
			var bitmap = GetBitmap(assembly, resourceName, makeTransparent);

			if (bitmap.Size != size)
			{
				throw new ArgumentException(string.Format("Image size is not valid. Must be {0}.", size));
			}

			return bitmap;
		}

		/// <exception cref="ArgumentException"><c>ArgumentException</c>.</exception>
		private static Stream CreateStream(Assembly assembly, string resourceName)
		{
			var fullName = assembly.GetName().Name + "." + resourceName;
			var stream = assembly.GetManifestResourceStream(fullName);

			if (stream == null)
			{
				var message = 
					string
						.Format(
							"Cannot find the resource \"{0}\" in the assembly \"{1}\".", 
							fullName, 
							assembly.FullName);

				throw new ArgumentException(message);
			}

			return stream;
		}
	}
}